<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>统计对应次数</title>
  </head>
  <body>
    <script>
      const obj1 = [
        { id: 1, parent_id: 1 },
        { id: 2, parent_id: 1 },
        { id: 3, parent_id: 5 },
        { id: 4, parent_id: 2 },
        { id: 5, parent_id: 1 },
        { id: 6, parent_id: 5 },
      ];

      const obj2 = [
        { id: 1, count: 0 },
        { id: 2, count: 0 },
        { id: 5, count: 0 },
      ];
      // method1:(差)
      /*for (let i = 0; i < obj2.length; i++) {
        let id = obj2[i].id;
        let count = 0;
        for (let i = 0; i < obj1.length; i++) {
            if (obj1[i].parent_id === id) {
                count++;
            }
        }
        obj2[i].count = count;
    }*/

      // method2:(好)
      let hash = {};
      for (let i = 0; i < obj1.length; i++) {
        if (!hash[obj1[i].parent_id]) {
          hash[obj1[i].parent_id] = 1;
        } else {
          hash[obj1[i].parent_id]++;
        }
      }
      for (let i = 0; i < obj2.length; i++) {
        obj2[i].count = hash[obj2[i].id];
      }
      console.log(hash);
      console.log(obj2);
    </script>
  </body>
</html>
